#!/usr/bin/env python3
"""
权限管理系统演示脚本
展示如何使用新的权限功能
"""

import requests
import json

BASE_URL = "http://localhost:8000/api"

def get_auth_token(username, password):
    """获取认证token"""
    response = requests.post(f"{BASE_URL}/auth/login", json={
        "username": username,
        "password": password
    })
    if response.status_code == 200:
        return response.json()["access_token"]
    return None

def create_demo_folder(token, name, parent_id=None):
    """创建演示文件夹"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post(f"{BASE_URL}/files/folder", json={
        "name": name,
        "parent_id": parent_id
    }, headers=headers)
    
    if response.status_code == 200:
        return response.json()["id"]
    return None

def set_folder_department_permission(token, folder_id, department_id, permission_type):
    """设置文件夹部门权限"""
    headers = {"Authorization": f"Bearer {token}"}
    
    # 根据权限类型设置具体权限
    permissions = {
        "read": {"target_id": department_id, "can_read": True, "can_write": False, "can_delete": False},
        "write": {"target_id": department_id, "can_read": True, "can_write": True, "can_delete": False},
        "manage": {"target_id": department_id, "can_read": True, "can_write": True, "can_delete": True}
    }
    
    response = requests.post(f"{BASE_URL}/permissions/folder/{folder_id}/department", 
                           json=permissions.get(permission_type, permissions["read"]), 
                           headers=headers)
    return response.status_code == 200

def set_folder_user_permission(token, folder_id, user_id, permission_type):
    """设置文件夹用户权限"""
    headers = {"Authorization": f"Bearer {token}"}
    
    # 根据权限类型设置具体权限
    permissions = {
        "read": {"target_id": user_id, "can_read": True, "can_write": False, "can_delete": False},
        "write": {"target_id": user_id, "can_read": True, "can_write": True, "can_delete": False},
        "manage": {"target_id": user_id, "can_read": True, "can_write": True, "can_delete": True}
    }
    
    response = requests.post(f"{BASE_URL}/permissions/folder/{folder_id}/user", 
                           json=permissions.get(permission_type, permissions["read"]), 
                           headers=headers)
    return response.status_code == 200

def get_folder_permissions(token, folder_id):
    """获取文件夹权限"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"{BASE_URL}/permissions/folder/{folder_id}", headers=headers)
    if response.status_code == 200:
        return response.json()
    return None

def get_departments(token):
    """获取部门列表"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"{BASE_URL}/departments/", headers=headers)
    if response.status_code == 200:
        return response.json()
    return []

def get_users(token):
    """获取用户列表"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"{BASE_URL}/users/", headers=headers)
    if response.status_code == 200:
        return response.json()
    return []

def main():
    print("🚀 权限管理系统演示")
    print("=" * 60)
    
    # 1. 管理员登录
    print("1. 管理员登录...")
    admin_token = get_auth_token("admin", "admin123")
    if not admin_token:
        print("❌ 管理员登录失败")
        return
    print("✅ 管理员登录成功")
    
    # 2. 获取部门和用户信息
    print("\n2. 获取系统信息...")
    departments = get_departments(admin_token)
    users = get_users(admin_token)
    
    print(f"📋 部门数量: {len(departments)}")
    for dept in departments:
        print(f"   - {dept['name']} (ID: {dept['id']})")
    
    print(f"👥 用户数量: {len(users)}")
    for user in users:
        print(f"   - {user['username']} (ID: {user['id']}, 角色: {user['role']})")
    
    # 3. 创建演示文件夹
    print("\n3. 创建演示文件夹...")
    folder_id = create_demo_folder(admin_token, "权限演示文件夹")
    if not folder_id:
        print("❌ 创建文件夹失败")
        return
    print(f"✅ 创建文件夹成功 (ID: {folder_id})")
    
    # 4. 设置部门权限
    if departments:
        print("\n4. 设置部门权限...")
        dept_id = departments[0]['id']
        success = set_folder_department_permission(admin_token, folder_id, dept_id, "read")
        if success:
            print(f"✅ 为部门 '{departments[0]['name']}' 设置只读权限成功")
        else:
            print("❌ 设置部门权限失败")
    
    # 5. 设置用户权限
    regular_users = [u for u in users if u['role'] == 'user']
    if regular_users:
        print("\n5. 设置用户权限...")
        user_id = regular_users[0]['id']
        success = set_folder_user_permission(admin_token, folder_id, user_id, "write")
        if success:
            print(f"✅ 为用户 '{regular_users[0]['username']}' 设置读写权限成功")
        else:
            print("❌ 设置用户权限失败")
    
    # 6. 查看权限设置结果
    print("\n6. 查看权限设置结果...")
    permissions = get_folder_permissions(admin_token, folder_id)
    if permissions:
        print("📁 文件夹权限详情:")
        dept_perms = permissions.get('department_permissions', [])
        print(f"   部门权限: {len(dept_perms)} 个")
        for dept_perm in dept_perms:
            perm_level = "管理" if dept_perm.get('can_delete') else ("读写" if dept_perm.get('can_write') else "只读")
            print(f"     - {dept_perm.get('department_name', '未知部门')}: {perm_level}")
        
        user_perms = permissions.get('user_permissions', [])
        print(f"   用户权限: {len(user_perms)} 个")
        for user_perm in user_perms:
            perm_level = "管理" if user_perm.get('can_delete') else ("读写" if user_perm.get('can_write') else "只读")
            print(f"     - {user_perm.get('username', '未知用户')}: {perm_level}")
    
    # 7. 测试普通用户访问
    if regular_users:
        print("\n7. 测试普通用户访问...")
        user_token = get_auth_token(regular_users[0]['username'], "user123")
        if user_token:
            print(f"✅ 用户 '{regular_users[0]['username']}' 登录成功")
            
            # 尝试访问文件夹权限
            user_permissions = get_folder_permissions(user_token, folder_id)
            if user_permissions:
                print("✅ 用户可以查看文件夹权限")
            else:
                print("❌ 用户无法查看文件夹权限")
        else:
            print("❌ 普通用户登录失败")
    
    print("\n" + "=" * 60)
    print("🎉 权限管理系统演示完成！")
    print("\n💡 功能亮点:")
    print("   • 支持文件夹级别的权限控制")
    print("   • 可以为部门和用户分别设置权限")
    print("   • 权限级别：只读(read)、读写(write)、管理(manage)")
    print("   • 支持文件共享级别设置")
    print("   • 管理员可以管理所有权限")

if __name__ == "__main__":
    main()